#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
应用程序设置管理模块
处理配置的加载、保存和监控
"""

import json
import logging
import os
import base64
from pathlib import Path
from typing import Dict, Any, Optional

from config.constants import CONFIG_DIR, CONFIG_FILE, DEFAULT_THEME, MAX_RECENT_FILES

# 初始化日志记录器
logger = logging.getLogger("settings")


class Settings:
    """应用程序设置管理类"""
    
    _instance = None
    
    def __new__(cls):
        """单例模式实现"""
        if cls._instance is None:
            cls._instance = super(Settings, cls).__new__(cls)
            cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        """初始化设置管理器"""
        if self._initialized:
            return
            
        self._initialized = True
        self._settings = {}
        self._default_settings = {
            "theme": DEFAULT_THEME,
            "language": "auto",  # 默认跟随系统
            "recent_files": [],
            "window_state": None,
            "default_encoding": "UTF-8",
            "csv_delimiter": ",",
            "auto_save_queries": True,
            "query_timeout": 30,
            "editor_font_family": "Consolas",  # 编辑器字体
            "editor_font_size": 12,  # 编辑器字体大小
            "enable_editor_wheel_zoom": True,  # 启用编辑器Ctrl+滚轮缩放
        }
        
        # 确保配置目录存在
        os.makedirs(CONFIG_DIR, exist_ok=True)
        
        # 加载设置
        self.load_settings()
    
    def load_settings(self) -> bool:
        """从文件加载设置
        
        Returns:
            加载成功标志
        """
        try:
            if not CONFIG_FILE.exists():
                logger.info("配置文件不存在，使用默认设置")
                self._settings = self._default_settings.copy()
                return True
                
            with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                loaded_settings = json.load(f)
                
            # 合并默认设置和加载的设置
            self._settings = self._default_settings.copy()
            self._settings.update(loaded_settings)
            
            logger.info("成功加载配置文件")
            return True
            
        except Exception as e:
            logger.error(f"加载配置文件失败: {str(e)}")
            self._settings = self._default_settings.copy()
            return False
    
    def save_settings(self) -> bool:
        """保存设置到文件
        
        Returns:
            保存成功标志
        """
        try:
            with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
                json.dump(self._settings, f, ensure_ascii=False, indent=2)
                
            logger.info("成功保存配置文件")
            return True
            
        except Exception as e:
            logger.error(f"保存配置文件失败: {str(e)}")
            return False
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取设置值
        
        Args:
            key: 设置键名
            default: 默认值，如果键不存在
            
        Returns:
            设置值
        """
        return self._settings.get(key, default)
    
    def set(self, key: str, value: Any) -> None:
        """设置值
        
        Args:
            key: 设置键名
            value: 设置值
        """
        self._settings[key] = value
        
    def add_recent_file(self, file_path: str) -> None:
        """添加最近打开的文件
        
        Args:
            file_path: 文件路径
        """
        recent_files = self.get("recent_files", [])
        
        # 如果已存在，先移除
        if file_path in recent_files:
            recent_files.remove(file_path)
            
        # 添加到最前面
        recent_files.insert(0, file_path)
        
        # 限制数量
        if len(recent_files) > MAX_RECENT_FILES:
            recent_files = recent_files[:MAX_RECENT_FILES]
            
        self.set("recent_files", recent_files)
        
    def get_recent_files(self) -> list:
        """获取最近打开的文件列表
        
        Returns:
            文件路径列表
        """
        return self.get("recent_files", [])
    
    def save_window_state(self, state) -> None:
        """保存窗口状态
        
        Args:
            state: 窗口状态对象（二进制数据）
        """
        if state is not None:
            # 将二进制数据转换为Base64编码的字符串
            encoded_state = base64.b64encode(state).decode('ascii')
            self.set("window_state", encoded_state)
        else:
            self.set("window_state", None)
        self.save_settings()
        
    def reset_to_defaults(self) -> None:
        """重置所有设置为默认值"""
        self._settings = self._default_settings.copy()
        self.save_settings()


# 导出单例实例
settings = Settings()
